import tkinter as tk
from tkinter import scrolledtext, messagebox, ttk
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def format_json(json_string):
    try:
        parsed_json = json.loads(json_string)
        formatted_json = json.dumps(parsed_json, indent=4, ensure_ascii=False)
        return formatted_json
    except json.JSONDecodeError as e:
        return f"无效的JSON字符串: {e}"

def populate_tree(tree, parent, data):
    if isinstance(data, dict):
        for key, value in data.items():
            if isinstance(value, (dict, list)):
                node = tree.insert(parent, 'end', text=key, open=False)
                populate_tree(tree, node, value)
            else:
                tree.insert(parent, 'end', text=f"{key}: {value}")
    elif isinstance(data, list):
        list_node = tree.insert(parent, 'end', text=f"列表 ({len(data)} 项)", open=False)
        for index, item in enumerate(data):
            item_node = tree.insert(list_node, 'end', text=f"对象 {index}", open=False)
            populate_tree(tree, item_node, item)
    else:
        tree.insert(parent, 'end', text=str(data))

def on_format_button_click():
    input_json = input_text.get("1.0", tk.END).strip()
    formatted_json = format_json(input_json)
    output_text.delete("1.0", tk.END)
    output_text.insert(tk.END, formatted_json)

    try:
        parsed_json = json.loads(input_json)
        tree.delete(*tree.get_children())
        populate_tree(tree, '', parsed_json)
    except json.JSONDecodeError as e:
        messagebox.showerror("错误", f"无效的JSON字符串: {e}")

# 创建主窗口
root = tk.Tk()
root.title("JSON Formatter")
root.geometry("1200x800")

# 使用 Grid 布局管理器
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=2)  # 增加输入框的高度
root.grid_rowconfigure(2, weight=1)  # 减少格式化按钮的高度
root.grid_rowconfigure(3, weight=2)  # 增加输出框的高度
root.grid_rowconfigure(4, weight=2)  # 增加输出框的高度
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)

# 输入框
input_label = tk.Label(root, text="输入JSON字符串:")
input_label.grid(row=0, column=1, padx=5, pady=2, sticky='w')
input_text = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=70, height=10)
input_text.grid(row=1, column=1, padx=10, pady=5, sticky='nsew')

# 格式化按钮
format_button = tk.Button(root, text="格式化", command=on_format_button_click, bg='lightblue', bd=2, relief=tk.RAISED)
format_button.grid(row=2, column=1, padx=10, pady=2, sticky='ew')  # 减少垂直方向的填充

# 输出框
output_label = tk.Label(root, text="格式化后的JSON:")
output_label.grid(row=3, column=1, padx=5, pady=2, sticky='w')
output_text = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=70, height=15)  # 增加输出框的高度
output_text.grid(row=4, column=1, padx=10, pady=5, sticky='nsew')

# 树形结构展示
tree_label = tk.Label(root, text="JSON树结构:")
tree_label.grid(row=0, column=0, padx=5, pady=2, sticky='w')

# 创建一个框架来容纳 Treeview 和滚动条
tree_frame = ttk.Frame(root)
tree_frame.grid(row=1, column=0, rowspan=4, padx=10, pady=5, sticky='nsew')
tree_frame.grid_rowconfigure(0, weight=1)
tree_frame.grid_columnconfigure(0, weight=1)
tree_frame.grid_columnconfigure(1, weight=0)

# 创建 Treeview
tree = ttk.Treeview(tree_frame, columns=("value"), show='tree')
tree.grid(row=0, column=0, sticky='nsew')

# 创建垂直滚动条
tree_scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=tree.yview)
tree_scrollbar.grid(row=0, column=1, sticky='ns')

# 将滚动条与 Treeview 关联
tree.configure(yscrollcommand=tree_scrollbar.set)

# 运行主循环
root.mainloop()
